package org.terraz.lcs {
	import flash.events.MouseEvent;
	import flash.events.StatusEvent;
	import flash.net.LocalConnection;
	
	import bi.log.Logger;	

	/**
	 * @author TarGz
	 */
	public class Master extends Client{
		public const type : String  = "master";
		public function Master() {
			Lcs.getLcs().log("Master.Master()");
			slaves = new Array();
			bouton = new Bouton();
			bouton.draw(300,0,100,100,0x000000);
			bouton.addEventListener(MouseEvent.MOUSE_UP, onClick);
			this.addChild(bouton);
		}
		

		override public function init():void{
			Lcs.getLcs().log("Master.init()");
			connect();
		}
		

		public function onSlaveConnection(id:String):void{
			Lcs.getLcs().log("Master.onSlaveConnection("+id+")");
			slaveConnection.send(id,"onMasterMessage","hello dude : "+id);
			slaves.push(id);
		}
		public function onSlaveMessage(id:String):void{
			Lcs.getLcs().log("Master.onSlaveConnection("+id+")");
		}
		// PRIVATE
		private function connect():void{
			masterConnection = new LocalConnection();
			masterConnection.client = this;
			slaveConnection = new LocalConnection();
			slaveConnection.addEventListener(StatusEvent.STATUS, onSlaveStatus);
			try {
				Lcs.getLcs().log("Master.connect() : " + ConnectionID.master);
				masterConnection.connect(ConnectionID.master);
			} catch (error:ArgumentError) {
               Lcs.getLcs().log("Can't connect to "+ConnectionID.master+"...the connection name is already being used by another SWF");
            }			
		}
		

		 private function onSlaveStatus(event:StatusEvent):void {
        	Lcs.getLcs().log("Master.onSlaveStatus(event)");
            switch (event.level) {
                case "status":
                    Lcs.getLcs().log("Slave.send() succeeded");
                    break;
                case "error":
                     Lcs.getLcs().log("Slave.send() failed");
                    break;
            }
        }
        private function onClick(e : MouseEvent) : void {
        	Lcs.getLcs().log("Master.onClick(e)");
        	messageAllSlave();
		}
		
		private function messageAllSlave() : void {
			Logger.debug("Master.messageAllSlave()");
			for (var i : Number = 0; i < slaves.length; i++) {
				Logger.debug("slavesId = " + slaves[i]);
				messageSlave(slaves[i]);
			}
			
		}
		public function messageSlave(id:String ):void{
			Lcs.getLcs().log("Master.onSlaveConnection("+id+")");
			slaveConnection.send(id,"onMasterMessage","this is a message to you : "+id);
		}
		private var masterConnection : LocalConnection;
		private var slaveConnection : LocalConnection;
		private var bouton : Bouton;
		private var slaves : Array;
	}
}
